// 加载express
const express = require("express");
// 创建路由对象
const router = express.Router();
const path = require("path");
const db = require(path.join(__dirname, "../utils/db"));
// 加密模块
const utility = require("utility");
const jsonwebtoken = require("jsonwebtoken");
// 这里写接口

router.post("/login", async(req, res) => {
    let username = req.body.username;
    let password = utility.md5(req.body.password);

    let r = await db("select * from user where username=? and password=?", [
        username,
        password,
    ]);
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: "登录成功",
            token: "Bearer " +
                jsonwebtoken.sign({
                        username: req.body.username,
                        id: r[0].id,
                    },
                    "bigevent", {
                        expiresIn: "2 days",
                    }
                ),
        });
    } else {
        res.send({
            status: 1,
            message: "登录失败",
        });
    }
});

// 注册的接口
router.post("/reguser", async(req, res) => {
    // console.log(req.body);
    req.body.password = utility.md5(req.body.password);
    let result = await db("insert into user set?", req.body);

    // console.log(result, req.body);
    if (result && result.affectedRows > 0) {
        res.send({
            status: 0,
            message: "注册成功",
        });
    } else {
        res.send({
            status: 1,
            message: "注册失败",
        });
    }
});
// 导出路由对象
module.exports = router;